package com.zbkj.service.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.model.acticitystyle.ActivityStyle;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.agent.AttractActivityRecord;
import com.zbkj.common.model.brand.Brand;
import com.zbkj.common.model.user.User;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.AttractActivityFrontSearchRequest;
import com.zbkj.common.request.PageParamRequest;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;

import com.zbkj.common.response.*;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.CrmebDateUtil;
import com.zbkj.common.model.agent.AttractActivity;
import com.zbkj.service.dao.AttractActivityDao;
import com.zbkj.service.service.*;

import com.zbkj.common.request.AttractActivitySaveRequest;
import com.zbkj.common.request.AttractActivitySearchRequest;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.util.BrandUtil;
import jodd.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author Caiyc
* @description AttractActivityServiceImpl 接口实现
* @date 2025-08-07
*/
@Service
public class AttractActivityServiceImpl extends ServiceImpl<AttractActivityDao, AttractActivity> implements AttractActivityService {

    @Resource
    private AttractActivityDao dao;
    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Autowired
    private AttractActivityRecordService attractActivityRecordService;
    @Autowired
    private UserService userService;
    @Autowired
    private BrandService brandService;

    @Autowired
    private SystemAdminService systemAdminService;


    @Override
    public Boolean create(AttractActivitySaveRequest attractActivitySaveRequest) {
        AttractActivity attractActivity = new AttractActivity();
        BeanUtils.copyProperties(attractActivitySaveRequest, attractActivity, "id");
        attractActivity.setBrandId(BrandUtil.getBrandIdByUrl());
        if (StrUtil.isNotBlank(attractActivitySaveRequest.getImage())) {
            attractActivity.setImage(systemAttachmentService.clearPrefix(attractActivitySaveRequest.getImage()));
        }
        if (StrUtil.isNotBlank(attractActivitySaveRequest.getVideo())) {
            attractActivity.setVideo(systemAttachmentService.clearPrefix(attractActivitySaveRequest.getVideo()));
        }
        boolean save = save(attractActivity);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询邀约活动表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<AttractActivity>
     * @author Caiyc
     * @since 2025-08-07
     */
    @Override
    public List<AttractActivityPageDataResponse> getList(AttractActivitySearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<AttractActivity> lambdaQueryWrapper = Wrappers.lambdaQuery();
        if (ObjectUtil.isNotEmpty(request.getTitle())) {
            lambdaQueryWrapper.like(AttractActivity::getTitle, URLUtil.decode(request.getTitle()));
        }
        lambdaQueryWrapper.eq(AttractActivity::getBrandId, BrandUtil.getBrandIdByUrl());
        lambdaQueryWrapper.eq(AttractActivity::getIsDel, false);

        lambdaQueryWrapper.orderByDesc(AttractActivity::getCreateTime);
        List<AttractActivity> attractActivitys = dao.selectList(lambdaQueryWrapper);
        // 添加活动状态
        List<AttractActivityPageDataResponse> attractActivityResponses = new ArrayList<>();

        attractActivitys.stream().forEach(x->{
            AttractActivityPageDataResponse attractActivityResponse = new AttractActivityPageDataResponse();
            BeanUtils.copyProperties(x, attractActivityResponse);
            attractActivityResponses.add(attractActivityResponse);
        });
        return attractActivityResponses;
    }

    @Override
    public PageInfo<AttractActivityFrontPageDataResponse> getListH5(AttractActivityFrontSearchRequest request, PageParamRequest pageParamRequest) {
        Page<AttractActivity> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<AttractActivity> lambdaQueryWrapper = Wrappers.lambdaQuery();
        if (ObjectUtil.isNotEmpty(request.getTitle())) {
            lambdaQueryWrapper.like(AttractActivity::getTitle, URLUtil.decode(request.getTitle()));
        }
        lambdaQueryWrapper.eq(AttractActivity::getBrandId, BrandUtil.getBrandIdByUrl());
        lambdaQueryWrapper.eq(AttractActivity::getIsDel, false);
        lambdaQueryWrapper.eq(AttractActivity::getStatus, 1);

        lambdaQueryWrapper.orderByDesc(AttractActivity::getCreateTime);
        List<AttractActivity> attractActivitys = dao.selectList(lambdaQueryWrapper);
        // 添加活动状态
        List<AttractActivityFrontPageDataResponse> attractActivityResponses = new ArrayList<>();

        attractActivitys.stream().forEach(x->{
            AttractActivityFrontPageDataResponse attractActivityResponse = new AttractActivityFrontPageDataResponse();
            BeanUtils.copyProperties(x, attractActivityResponse);
            attractActivityResponses.add(attractActivityResponse);
        });
        return CommonPage.copyPageInfo(page, attractActivityResponses);
    }

    /**
    * 修改邀约活动表
    * @param request
    * @return
    */
    @Override
    public boolean update(AttractActivitySaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入邀约活动ID");
        }
        getByIdException(request.getId());
        AttractActivity attractActivity = new AttractActivity();
        BeanUtils.copyProperties(request, attractActivity);
        if (StrUtil.isNotBlank(request.getImage())) {
            attractActivity.setImage(systemAttachmentService.clearPrefix(request.getImage()));
        }
        if (StrUtil.isNotBlank(request.getVideo())) {
            attractActivity.setVideo(systemAttachmentService.clearPrefix(request.getVideo()));
        }
        return updateById(attractActivity);
    }

    private AttractActivity getByIdException(Integer id) {
        AttractActivity attractActivity = getById(id);
        if (ObjectUtil.isNull(attractActivity)) {
            throw new AppException("邀约活动不存在");
        }
        if (attractActivity.getIsDel()) {
            throw new AppException("邀约活动不存在");
        }
        if (!attractActivity.getBrandId().equals(BrandUtil.getBrandIdByUrl())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "您没有权限操作此邀约活动");
        }
        return attractActivity;
    }

    /**
    * 批量删除
    * @param idList
    * @return
    */
    @Override
    public boolean batchDelete(List<Integer> idList) {
        LambdaUpdateWrapper<AttractActivity> luw = Wrappers.lambdaUpdate();
        luw.set(AttractActivity::getIsDel, true);
        luw.in(AttractActivity::getId, idList);
        luw.eq(AttractActivity::getBrandId, BrandUtil.getBrandIdByUrl());
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除邀约活动失败"));
        }
        return true;
    }

    /**
    * 查询详情
    * @param id
    * @return
    */
    @Override
    public AttractActivityDetailResponse getDetails(Integer id) {
        LambdaQueryWrapper<AttractActivity> lqw = Wrappers.lambdaQuery();
        lqw.eq(AttractActivity::getIsDel, 0);
        lqw.eq(AttractActivity::getBrandId, BrandUtil.getBrandIdByUrl());
        lqw.eq(AttractActivity::getId, id);
        lqw.last("limit 1");
        AttractActivity attractActivity = this.getOne(lqw);
        if (ObjectUtil.isNotNull(attractActivity)) {
            AttractActivityDetailResponse response = new AttractActivityDetailResponse();
            BeanUtils.copyProperties(attractActivity, response);
            return response;
        }
        return null;
    }

    @Override
    public AttractActivityFrontDetailResponse getDetailsH5(Integer id) {
        User user = userService.getInfo();
        LambdaQueryWrapper<AttractActivity> lqw = Wrappers.lambdaQuery();
        lqw.eq(AttractActivity::getIsDel, 0);
         Integer brandId = BrandUtil.getBrandIdByUrl();

        SystemAdmin systemAdmin = systemAdminService.getById(brandId);
        String brandName = "";
        if(systemAdmin!=null && systemAdmin.getBrandId()!=null){
            Brand brand = brandService.getById(systemAdmin.getBrandId());
            if(brand!=null){
                brandName = brand.getName();
            }
        }


        lqw.eq(AttractActivity::getBrandId, brandId);
        lqw.eq(AttractActivity::getId, id);
        lqw.last("limit 1");
        AttractActivity attractActivity = this.getOne(lqw);
        if (ObjectUtil.isNotNull(attractActivity)) {
            AttractActivityFrontDetailResponse response = new AttractActivityFrontDetailResponse();
            BeanUtils.copyProperties(attractActivity, response);
            if (!StringUtil.isEmpty(brandName)){
                response.setTitle(brandName + "-" + response.getTitle());
            }

            // 当前用户是否已填写
            int countByUid = attractActivityRecordService.getCountByUid(attractActivity.getId(), user.getId());
            response.setIsFill(countByUid > 0);
            return response;
        }
        return null;
    }

    @Override
    public AttractActivityLatestFrontResponse getLatestActivity() {
        LambdaQueryWrapper<AttractActivity> lqw = Wrappers.lambdaQuery();
        lqw.eq(AttractActivity::getIsDel, 0);
        lqw.eq(AttractActivity::getStatus, 1);
        lqw.eq(AttractActivity::getBrandId, BrandUtil.getBrandIdByUrl());
        lqw.orderByDesc(AttractActivity::getCreateTime);
        lqw.last("limit 1");
        AttractActivity attractActivity = this.getOne(lqw);
        if (ObjectUtil.isNotNull(attractActivity)) {
            AttractActivityLatestFrontResponse response = new AttractActivityLatestFrontResponse();
            BeanUtils.copyProperties(attractActivity, response);
            return response;
        }
        return null;
    }

    @Override
    public String getTitleById(Integer activityId) {
        LambdaQueryWrapper<AttractActivity> lqw = Wrappers.lambdaQuery();
        lqw.eq(AttractActivity::getIsDel, 0);
        lqw.eq(AttractActivity::getId, activityId);
        AttractActivity attractActivity = this.getOne(lqw);
        if (ObjectUtil.isNotNull(attractActivity)) {
            return attractActivity.getTitle();
        }
        return null;
    }

    @Override
    public boolean updateStatus(Integer id, Integer status) {
        AttractActivity activityStyle = new AttractActivity();
        activityStyle.setId(id);
        activityStyle.setStatus(status);
        return updateById(activityStyle);
    }

    @Override
    public boolean copy(Integer id) {
        LambdaQueryWrapper<AttractActivity> lqw = Wrappers.lambdaQuery();
        lqw.eq(AttractActivity::getIsDel, 0);
        lqw.eq(AttractActivity::getBrandId, BrandUtil.getBrandIdByUrl());
        lqw.eq(AttractActivity::getId, id);
        lqw.last("limit 1");
        AttractActivity attractActivity = this.getOne(lqw);
        if (ObjectUtil.isNull(attractActivity)) {
            throw new AppException("邀约活动不存在");
        }
        if (!attractActivity.getBrandId().equals(BrandUtil.getBrandIdByUrl())) {
            throw new AppException("您无权操作该活动");
        }
        // 复制活动
        AttractActivity newActivity = new AttractActivity();
        BeanUtils.copyProperties(attractActivity, newActivity);
        newActivity.setId(null);
        newActivity.setBrandId(BrandUtil.getBrandIdByUrl());
        Date date = new Date();
        newActivity.setCreateTime(date);
        newActivity.setUpdateTime(date);
        save(newActivity);
        return true;
    }

}

